package com.dev.utils;

import com.dev.receiver.BatterySubscriber;
import ohos.aafwk.ability.AbilitySlice;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;

/**
 * 监听电量变化的工具类
 */
public class BatteryUtils {

    /**
     * 初始化电量监听过滤器
     *
     * @param slice
     * @return
     */
    public static BatterySubscriber initMatch(AbilitySlice slice) {
        MatchingSkills match = new MatchingSkills();
        match.addEvent(BatterySubscriber.COMMON_EVENT_BATTERY_CHANGED);
        match.addEvent(BatterySubscriber.COMMON_EVENT_BATTERY_LOW);
        match.addEvent(BatterySubscriber.COMMON_EVENT_BATTERY_OKAY);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(match);
        subscribeInfo.setPriority(100);
        BatterySubscriber subscriber = new BatterySubscriber(subscribeInfo, slice);
        return subscriber;
    }

    /**
     * 订阅电池改变事件
     *
     * @param subscriber
     */
    public static void subscriberBattery(BatterySubscriber subscriber) {
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtils.warn("WIFI", "subscribe in battery events failed!");
        }
    }

    /**
     * 取消订阅电池改变事件
     */
    public static void unSubscribeBattery(BatterySubscriber subscriber) {
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtils.warn("WIFI", "unsubscribe in battery events failed!");
        }
    }
}
